package com.jingdianchi.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jingdianchi.gateway.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展 
 */
@Component
@Slf4j
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private RedisUtil redisUtil;

    String authPermissionPrefix = "auth.permission";
    String authRolePrefix = "auth.role";


    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return getAuth(loginId.toString(),authPermissionPrefix);
    }

    private List<String> getAuth(String loginId, String prefix) {
        String authKey = redisUtil.buildKey(prefix,loginId);
        String authValue = redisUtil.get(authKey);
        log.info("{}:{}",authKey,authValue);
        if(StringUtils.isBlank(authValue)){
            return Collections.emptyList();
        }
        List<String> authList = new Gson().fromJson(authValue, new TypeToken<List<String>>() {}.getType());
        log.info("authList:{}",authList);
        /*if(prefix.equals(authPermissionPrefix)){
            List<AuthPermission> permissionList =
                    new Gson().fromJson(authValue, new TypeToken<List<String>>() {}.getType());
            authList = permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        }else if(prefix.equals(authRolePrefix)){
            List<AuthRole> roleList = new Gson().fromJson(authValue, new TypeToken<List<String>>() {}.getType());
            authList = roleList.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());
        }*/
        return authList;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getAuth(loginId.toString(),authRolePrefix);
    }

}
